#include <thread>

#include "logger/logger.hpp"
#include "clocker/clocker.h"
#include "./smart/smart_mpp_decoder.hpp"
#include "./smart/h264_file_nalu_pars.h"

int main(const int argc, const char* argv[])
{
    if (argc != 2) {
        printf("./tst_decode_h264 [filename.h264]\n");
        exit(EXIT_FAILURE);
    } else {
        printf("> %s %s\n", argv[0], argv[1]);
    }
    SmartMppDecoder mpp_dec(MPP_VIDEO_CodingAVC);
    H264FileNaluPars h264_nalu;
    FILE* decoded_fd;

    decoded_fd = fopen("test.yuv", "wb");
    if (decoded_fd == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    h264_nalu.init(argv[1], H264FileNaluPars::FMT_H264);

    /* 取帧并作处理 */
    while (true) {
        getchar();
        std::vector<uint8_t> buff = h264_nalu.get_nalu_frame();
        if (buff.size() <= 0) {
            log_debug("> file open end.");
            mpp_dec.stop();
            break;
        }
        while (buff.size() < 100) {
            std::vector<uint8_t> tmp_data = h264_nalu.get_nalu_frame();
            if (tmp_data.size() == 0) {
                printf("End of file reading.\n");
                continue;
            }
            buff.insert(buff.end(), tmp_data.begin(), tmp_data.end());
        }
        log_debug("<--- dec_put_buf: size %d.", buff.size());
        clocker_begin();
        printf("\n--- buff.size():%d ---\n", buff.size());
        mpp_dec.sync_decoding(buff.data(), buff.size(), [](uint8_t* frm_buf, uint32_t frm_len){
            log_info("get frame seccess, frm_buf:%p, frm_len:%d.", frm_buf, frm_len);
        });
        log_error("--- debug ---");
    }


    log_debug("--------- end ---------");
    fclose(decoded_fd);
    mpp_dec.deinit();
    h264_nalu.deinit();
}